package reflection;

import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;

public class MethodFieldDemo {
	private String name = "jie";
	public Integer age = 222;
	public static String staticFiled = "staticFiledvalue";

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Integer getAge() {
		return age;
	}

	public void setAge(Integer age) {
		this.age = age;
	}
	public Integer getA(Integer i){
		return i;
	}
	public static void staticMethod(Integer i){
		System.out.println(i);
	}

	public static void main(String[] args) throws Exception {
		//t1();
		//t2();
		//t3();
		t4();
	}
	public static void t4() throws Exception, IllegalAccessException{
		Class<MethodFieldDemo> clazz=MethodFieldDemo.class;
		MethodFieldDemo instance=clazz.newInstance();
		System.out.println(instance.getA(1));
		//获取带参数的实例
		Class<Integer>[] argClazz=new Class[1];
		argClazz[0]=Integer.class;
		Constructor<MethodFieldDemo> constructor=clazz.getConstructor(argClazz);
		constructor.newInstance(argClazz);
	}
	
	public static void  t3() throws Exception, SecurityException{
		MethodFieldDemo md = new MethodFieldDemo();
		Class<?> clazz=md.getClass();
		//获取每个参数的类型
		Class<Integer>[] argClazz=new Class[1];
		argClazz[0]=Integer.class;
		Method method=clazz.getMethod("getA",argClazz);
		System.out.println(method.invoke(md, 1));
		Method methodStatic=clazz.getMethod("staticMethod", argClazz);
		//执行静态方法
		System.out.println(methodStatic.invoke(null, 1));
	}

	public static void t2() throws Exception{
		MethodFieldDemo md = new MethodFieldDemo();
		Field field=md.getClass().getField("age");//获取这个字段
		System.out.println(field.get(md));//获取对象这个字段的值
		Field staticField=md.getClass().getField("staticFiled");
		System.out.println(staticField.get(md.getClass()));//如果是静态的直接从类里面读取
	}

	public static void t1() throws Exception {
		MethodFieldDemo md = new MethodFieldDemo();
		Field[] fields = md.getClass().getFields();
		for (Field field : fields) {
			System.out.println(field.get(md) + "获取public字段");
			System.out.println(field.getName());
		}
	}

}
